import { ref } from "vue";
import _ from "lodash"
/**
 * 最大导出数量
 */
const MAX_COUNT = 9999;
export function usePage({
    api_fn = () => { },
    q_data = {}
}) {
    const loading = ref(false)
    // 表格数据
    const data = ref([]);
    /**
     * 分页数据的总数量
     */
    const total = ref(0)
    /**
     * 分页数据
     */
    const page_data = ref({
        currentPage: 1,
        pageSize: 10
    })
    /**
     * 查询数据
     */
    const query_data = ref({
        ...q_data
    })
    /**
     * 加载状态
     */
    const loadding = ref(false)

    /**
     * 获取列表
     */
    const handleGetList = async () => {
        loading.value = true;
        let res = await api_fn({
            ...page_data.value,
            ...query_data.value
        });
        if (res.success) {
            data.value = res.pageInfo.list;
            total.value = res.pageInfo.total;
        }
        loading.value = false;
    }
    /**
     * 加载
     */
    const handleLoad = (bool = false) => {
        if (bool) {
            page_data.value.currentPage = 1;
            total.value = 0;
            data.value = [];
        }
        handleGetList();
    }
    /**
     * 分页切换
     */
    const handlePage = (page) => {
        page_data.value.currentPage = page;
        handleLoad();
    }
    /**
     * 自定义获取列表
     * condition null-无条件  current-当前条件
     * type page-当前页  all-全部页
     * @returns 
     */
    const handleGetCustomList = async (option = {
        condition: "null",
        type: "page",
    }

    ) => {
        let data = {};
        if (option.type == 'page') {
            data = _.merge(data, _.cloneDeep({
                ...page_data.value
            }))
        } else if (option.type == 'all') {
            data.currentPage = page_data.value.currentPage;
            data.pageSize = MAX_COUNT;
        }
        if (option.condition == 'current') {
            data = _.merge(data, _.cloneDeep(query_data.value))
        }
        let res = await api_fn(data);
        if (res.success) {
            return [true, res.pageInfo.list, res];
        } else {
            return [false, [], res];
        }
    }

    return {
        data,
        total,
        loading,
        query_data,
        handleLoad,
        handlePage,
        handleGetCustomList
    }
}